import {_decorator, Prefab, Node, resources, error, instantiate, find} from "cc";
import {Constant} from "../../config/Constant";

const {ccclass} = _decorator;

@ccclass("ResourceUtil")
export class ResourceUtil {
    /**
     * 加载单个资源(传统回调处理)
     * @param url   资源路径
     * @param type  资源类型
     * @param cb    回调
     * @method loadRes
     */
    public static loadRes(url: string, type: any, cb?: Function) {
        console.log("loadRes")
        resources.load(url, (err: any, res: any) => {
            if (err) {
                error(err.message || err);
                cb(err, res);
                return;
            }

            cb && cb(null, res);
        })
    }


    /**
     * 加载单个资源(异步处理)
     * @param url   资源路径
     * @param type  资源类型
     * @method loadRes
     */
    public static loadResType(url: string, type: any): Promise<any> {
        // Promise((resolve[成功时的调用桉树], reject[失败的异步函数])
        return new Promise((resolve, reject) => {
            resources.load(url, type, (err: any, res: any) => {
                if (err) {
                    error(err.message || err);
                    reject(err)
                    return;
                }
                resolve(res);
            })
        })
    }

    /**
     * 加载资源目录(异步处理)
     * @param url   资源路径
     * @param type  资源类型
     * @method loadRes
     */
    public static loadResDirType(url: string, type: any): Promise<any> {
        return new Promise((resolve, reject) => {
            resources.loadDir(url, type,(err,assets) => {
                if (err) {
                    error(err.message || err);
                    reject(err)
                    return;
                }
                resolve(assets);
            });
        })
    }

    /**
     * 创建ui界面
     * @param path ui路径
     * @param cb 回调函数
     */
    public static createUI(path: string, cb?: Function) {
        this.loadRes(Constant.DYNAMIC_RESOURCE.UiDialog.Path + path, Prefab, function (err: {}, prefab: Prefab) {
            if (err) return;
            let node: Node = instantiate(prefab);
            cb && cb(null, node);
        });
    }
}
